<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意只允许为第三级分类设置相关参数" :closable="false" show-icon type="warning"></el-alert>
      <el-row>
        <span>选择当前商品分类：</span>
        <el-cascader
          clearable
          v-model="currentCate"
          :options="categories"
          :props="cascaderconfig"
          @change="handleChange"
        ></el-cascader>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            :disabled="isbtnDisAble"
            type="primary"
            size="mini"
            @click="showManyParams"
          >添加参数</el-button>
          <el-table :expand-change="showValInfo" border :data="manyParamsList" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                <!-- {{scope.row.attr_vals}} -->
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                  @click="editParams(scope.row)"
                >编辑</el-button>
                <el-button
                  icon="el-icon-delete"
                  type="danger"
                  size="mini"
                  @click="delectParams(scope.row.attr_id)"
                >删除</el-button>
                <!-- <pre>
                  {{scope.row.attr_id}}
                </pre>-->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button
            :disabled="isbtnDisAble"
            type="primary"
            size="mini"
            @click="showOnlyParams"
          >添加参数</el-button>
          <el-table border :data="onlyParamsList" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                <!-- {{scope.row.attr_vals}} -->
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                  @click="editParams(scope.row)"
                >编辑</el-button>
                <el-button
                  icon="el-icon-delete"
                  type="danger"
                  size="mini"
                  @click="delectParams(scope.row.attr_id)"
                >删除</el-button>
                <!-- <pre>
                  {{scope.row.attr_id}}
                </pre>-->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加'+addCurrentParams"
      :visible.sync="addParamsVisible"
      width="50%"
      @close="closeAddParamsVisable"
    >
      <el-form :model="addParamsName" :rules="rules" ref="addParamsNameRef" label-width="100px">
        <el-form-item :label="addCurrentParams" prop="name">
          <el-input v-model="addParamsName.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="编辑参数"
      :visible.sync="editParamsVisible"
      width="50%"
      @close="closeeditParamsVisable"
    >
      <el-form :model="editParamsName" :rules="rules" ref="editParamsNameRef" label-width="100px">
        <el-form-item label="编辑参数" prop="name">
          <el-input v-model="editParamsName.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCurrentParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      activeName: "many",
      currentCate: [],
      categories: [],
      cascaderconfig: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      // 当前操作元素的id
      currentId: 0,
      // 获取到的参数列表数组 动态和静态
      manyParamsList: [],
      onlyParamsList: [],
      // 控制对话框属性
      addParamsVisible: false,
      addCurrentParams: "动态参数",
      // 新增参数信息
      addParamsName: {
        name: ""
      },
      // 控制编辑对话框属性
      editParamsVisible: false,
      // 编辑参数信息
      editParamsName: {
        name: ""
      },
      currentEditId: "",
      rules: {
        name: [{ required: true, message: "请输入参数名称", trigger: "blur" }]
      },
      detailParams: [],
      inputVisible:false,
      inputValue:''
    };
  },
  methods: {
    async getcategories() {
      const { data: res } = await this.$http.get("categories");

      if (res.meta.status !== 200) {
        return this.$message.error("获取商品数据失败");
      }
      this.categories = res.data;
    },
    handleChange() {
      this.getParamsList();
    },
    // 获取参数函数
    async getParamsList() {
      if (this.currentCate.length === 3) {
        this.currentId = this.currentCate[2];
        const { data: res } = await this.$http.get(
          `categories/${this.currentId}/attributes`,
          {
            params: { sel: this.activeName }
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("获取参数失败");
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
          item.inputVisible = false;
          item.inputValue = ''
        });
        console.log(res);
        if (this.activeName === "many") {
          this.manyParamsList = res.data;
        } else if (this.activeName === "only") {
          this.onlyParamsList = res.data;
        } else {
          return;
        }
      } else {
        this.currentCate = [];
        this.currentId = "";
        this.manyParamsList = [];
        this.onlyParamsList = [];
      }
    },
    // 点击切换tab标签栏
    handClick() {
      this.getParamsList();
    },
    showValInfo(row, expandedRows) {
      console.log(expandedRows);
    },
    // 打开添加参数列表
    showManyParams() {
      this.addParamsVisible = true;
      this.addCurrentParams = "动态参数";
    },
    showOnlyParams() {
      this.addParamsVisible = true;
      this.addCurrentParams = "静态参数";
    },
    // 关闭增加参数框清空元素
    closeAddParamsVisable() {
      this.$refs.addParamsNameRef.resetFields();
    },
    closeeditParamsVisable() {
      this.$refs.editParamsNameRef.resetFields();
    },
    //增加参数
    addParams() {
      this.$refs.addParamsNameRef.validate(async item => {
        if (!item) return;
        const { data: res } = await this.$http.post(
          `categories/${this.currentId}/attributes`,
          {
            attr_name: this.addParamsName.name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) {
          return this.$message.error("创建参数失败");
        }
        this.$message.success("创建参数成功");
        this.addParamsVisible = false;
        this.getParamsList();
      });
    },
    // 编辑参数
    editCurrentParams() {
      this.$refs.editParamsNameRef.validate(async item => {
        if (!item) return;
        const { data: res } = await this.$http.put(
          `categories/${this.currentId}/attributes/${this.currentEditId}`,
          {
            attr_name: this.editParamsName.name,
            attr_sel: this.activeName
          }
        );

        if (res.meta.status !== 200) {
          return this.$message.error("修改参数失败");
        }
        this.$message.success("修改参数成功");
        this.editParamsVisible = false;
        this.getParamsList();
      });
    },
    // 打开编辑参数弹出框
    async editParams(row) {
      this.editParamsVisible = true;
      this.currentEditId = row.attr_id;
      this.editParamsName.name = row.attr_name;
    },
    // 删除参数
    delectParams(attrId) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.currentId}/attributes/${attrId}`
          );
          if (res.meta.status !== 200) {
            return this.$message.error("删除参数失败");
          }
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getParamsList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 增加新的属性值
    handleInputConfirm(row){
      row.inputVisible= false;
      if(!row.inputValue.trim()){
        row.inputValue = ''
        return;
      }
      row.attr_vals.push(row.inputValue);
      row.inputValue=''
      this.operateParams(row)

    },
    showInput(row){
       row.inputVisible= true;
       this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    handleClose(i,row){
       row.attr_vals.splice(i,1);
       this.operateParams(row)
    },
    async operateParams(row){
       const { data: res } = await this.$http.put(
          `categories/${this.currentId}/attributes/${row.attr_id}`,
          {
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals:row.attr_vals.join(",")
          }
        );

        if (res.meta.status !== 200) {
          return this.$message.error("修改参数失败");
        }
        this.$message.success("修改参数成功");
    }
  },
  created() {
    this.getcategories();
  },
  computed: {
    isbtnDisAble() {
      if (this.currentCate.length !== 3) {
        return true;
      } else {
        return false;
      }
    }
  }
};
</script>
<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-tag {
  margin: 5px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>